﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Drawing;
using System.Security.Permissions;
using System.Reflection;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Drawing.Design;
using Fcdbas.Platform;
using Fcdbas.Core.Windows;
//using Fcdbas.Platform.Designers;
using Fcdbas.Platform.Enums;
using Fcdbas.WinUI.Design;
using Fcdbas.Platform.Properties;
using Fcdbas.WinUI.Windows;
using Fcdbas.Core.Reflection;
using Fcdbas.Core;
using Fcdbas.WinUI.Forms;
using Fcdbas.Platform.Controls;
using Fcdbas.Biz;

namespace Fcdbas.WinUI.Controls
{
    /// <summary>
    /// 3重新抽取,1抽取下一段,2抽取所有,4刷新当前对象
    /// </summary>
    public enum DataSourcePopulate
    {
        Next = 1,
        All = 2,
        RePopulate = 3,
        Current = 4

    }
    [Description("Fcdbas develop library datasource object.")]
    [Designer(typeof(DataSourceBindingDesigner))]
    [ToolboxBitmap(typeof(BindingSource))]
    [ToolboxItemFilter("System.Windows.Forms")]
    [SecurityPermissionAttribute(SecurityAction.LinkDemand)]
    [PropertyTab(typeof(F1PropertyTab), PropertyTabScope.Document)]
    public partial class DataSourceBinding : BindingSource, IWindowProperties, cDataSource.LateBind, ISalWindow//,Fcdbas.Platform.Interface.IEditableBusinessObject
    {
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordCheckModify method is called."), DisplayName("DataRecordCheckModify")]
        public event cDataSource.DataRecordCheckModifyEventHandler DataRecordCheckModify;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordCheckNew method is called."), DisplayName("DataRecordCheckNew")]
        public event cDataSource.DataRecordCheckNewEventHandler DataRecordCheckNew;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordCheckRemove method is called."), DisplayName("DataRecordCheckRemove")]
        public event cDataSource.DataRecordCheckRemoveEventHandler DataRecordCheckRemove;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordCheckRequired method is called."), DisplayName("DataRecordCheckRequired")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataRecordCheckRequired;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordDuplicate method is called.1是直接复制，2是从其他对象复制"), DisplayName("DataRecordDuplicate")]
        public event cDataSource.DataRecordDuplicateEventHandler DataRecordDuplicate;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordExecuteModify method is called."), DisplayName("DataRecordExecuteModify")]
        public event cDataSource.DataRecordExecuteModifyEventHandler DataRecordExecuteModify;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordExecuteNew method is called."), DisplayName("DataRecordExecuteNew")]
        public event cDataSource.DataRecordExecuteNewEventHandler DataRecordExecuteNew;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordExecuteRemove method is called."), DisplayName("DataRecordExecuteRemove")]
        public event cDataSource.DataRecordExecuteRemoveEventHandler DataRecordExecuteRemove;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordFetchEditedUser method is called."), DisplayName("DataRecordFetchEditedUser")]
        public event cDataSource.DataRecordFetchEditedUserEventHandler DataRecordFetchEditedUser;

        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordNew method is called."), DisplayName("DataRecordNew")]
        public event cDataSource.DataRecordNewEventHandler DataRecordNew;
        //[Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordNew method is called."), DisplayName("DataRecordEdit")]
        //public event cDataSource.DataRecordEditEventHandler DataRecordEditEvent;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordPrepareNew method is called."), DisplayName("DataRecordPrepareNew")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataRecordPrepareNew;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordRemove method is called."), DisplayName("DataRecordRemove")]
        public event cDataSource.DataRecordRemoveEventHandler DataRecordRemove;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordValidate method is called."), DisplayName("DataRecordValidate")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataRecordValidate;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceCheck method is called."), DisplayName("DataSourceCheck")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceCheck;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceClearIt method is called."), DisplayName("DataSourceClearIt")]
        public event cDataSource.DataSourceClearItEventHandler DataSourceClearIt;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceExecuteSqlDelete method is called."), DisplayName("DataSourceExecuteSqlDelete")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceExecuteSqlDelete;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceExecuteSqlInsert method is called."), DisplayName("DataSourceExecuteSqlInsert")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceExecuteSqlInsert;
       // [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceExecuteSqlSelect method is called."), DisplayName("DataSourceExecuteSqlSelect")]
       // public event cDataSource.DataSourceExecuteSqlSelectEventHandler DataSourceExecuteSqlSelectEvent;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceExecuteSqlUpdate method is called."), DisplayName("DataSourceExecuteSqlUpdate")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceExecuteSqlUpdateEvent;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceFieldModified method is called."), DisplayName("DataSourceFieldModified")]
        public event EventHandler<cDataSource.ReturnEventArgsSalNumber> DataSourceFieldModified;
       // [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceInquireSave method is called."), DisplayName("DataSourceInquireSave")]
      //  public event EventHandler<cDataSource.ReturnEventArgsSalNumber> DataSourceInquireSaveEvent;
      //  [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceIsDirty method is called."), DisplayName("DataSourceIsDirty")]
       // public event cDataSource.DataSourceIsDirtyEventHandler DataSourceIsDirtyEvent;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceSave method is called."), DisplayName("DataSourceSaves")]
        public event cDataSource.DataSourceSaveEventHandler DataSourceSaves;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceSaveCheck method is called."), DisplayName("DataSourceSaveCheck")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceSaveCheck;
        
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceDataChanged method is called."), DisplayName("DataSourceDataChanged")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceDataChanged;
        [Category("F1 Late Bind Events"), Description("当刷新当前记录时触发"), DisplayName("DataRecordCurrentRefresh")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataRecordCurrentRefresh;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceSaveMarkCommitted method is called."), DisplayName("DataSourceSaveMarkCommitted")]
        public event EventHandler<cDataSource.ReturnEventArgsSalNumber> DataSourceSaveMarkCommitted;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceSaveModified method is called."), DisplayName("DataSourceSaveModified")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceSaveModified;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceSaveNew method is called."), DisplayName("DataSourceSaveNew")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceSaveNew;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceSaveRemoved method is called."), DisplayName("DataSourceSaveRemoved")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceSaveRemoved;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataSourceValidate method is called."), DisplayName("DataSourceValidate")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataSourceValidate;
        [Category("F1 Late Bind Events"), Description("Occurs when the vrtDataRecordToFormUser method is called."), DisplayName("DataRecordToFormUser")]
        public event cDataSource.DataRecordToFormUserEventHandler DataRecordToFormUser;


        /// <summary>
        /// 打开数据查询并查询前发生，可在查询前干预,如果返回值为false，将不执行查询
        /// </summary>
        [Category("F1 Late Bind Events"), Description("当通过查询窗口查询数据时发生"), DisplayName("DataIsQuerying")]
        public event EventHandler<cDataSource.ReturnEventArgsSalBoolean> DataIsQuerying;
        /// <summary>
        /// 打开数据查询前发生，可在查询前干预,加入额外的条件进行查询
        /// </summary>
        [Category("F1 Late Bind Events"), Description("打开数据查询前发生，可在查询前干预,加入额外的条件进行查询"), DisplayName("DataIsQueryingWhere")]
        public event EventHandler<cDataSource.ReturnEventArgsSalString> DataIsQueryingWhere;

        [Category("F1 Late Bind Events"), Description("当数据查询前发生，可在查询前干预,改变条件进行查询"), DisplayName("DataSourceUserWhere")]
        public event EventHandler<cDataSource.ReturnEventArgsSalString> DataSourceUserWhere;

        [Category("F1 Late Bind Events"), Description("当数据抽取完成后触发"), DisplayName("FetchRowsDone")]
        public event EventHandler<cDataSource.ReturnEventArgsSalNumber> FetchRowsDone;
        

        private SalWindow m_salWindow;
        private cDataSource dataSource;
        //private object zeroList;
        #region Fcdbase 扩展属性
        private BaseForm _parentForm;
        public static bool UserDesignMode = false;
        //public IEntity OldEntity
        //{
        //    get;
        //    set;
        //}
        public List<IEntity> OldEntitys = new List<IEntity>();
        /// <summary>
        /// 界面绑定的字段列表
        /// </summary>
        [Browsable(true)]
        [DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Content)]
        public List<DataItem> Columns
        {
            get;
            set;
        }
        //public object ZeroList
        //{
        //    get{ return zeroList;}
        //}
        [Browsable(false)]
        public bool IsUserQuery
        {
            get;
            set;
        }
        [Browsable(false)]
        public bool IsUserNew
        {
            get;
            set;
        }
        [Browsable(false)]
        public bool IsUserModify
        {
            get;
            set;
        }
        /// <summary>
        /// 
        /// </summary>
        [Browsable(false)]
        public bool IsUserDelete
        {
            get;
            set;
        }
        public SalNumber OnFetchRowsDone(object sender,int nRecordCount)
        {
            if (FetchRowsDone != null)
            {
                cDataSource.ReturnEventArgsSalNumber ret = new cDataSource.ReturnEventArgsSalNumber();
                ret.ReturnValue = nRecordCount;
                FetchRowsDone.Invoke(sender, ret);
                return nRecordCount;
            }
            return nRecordCount;
        }
        public SalBoolean OnDataIsQuerying(object sender)
        {
            if (DataIsQuerying != null)
            {
                cDataSource.ReturnEventArgsSalBoolean ret = new cDataSource.ReturnEventArgsSalBoolean();
                DataIsQuerying.Invoke(sender, ret);
                //if (ret.Handled)
                return ret.ReturnValue;
            }
            return true;
        }
        public SalString OnDataIsQueryingWhere(object sender)
        {
            if (DataIsQueryingWhere != null)
            {
                cDataSource.ReturnEventArgsSalString ret = new cDataSource.ReturnEventArgsSalString();
                ret.ReturnValue = "";
                DataIsQueryingWhere.Invoke(sender, ret);
                //if (ret.Handled)
                return ret.ReturnValue;
            }
            return "";
        }
        public DataItem GetDataItemByColumnName(string columnName)
        {
            if (Columns == null)
                return null;
            return (from c in Columns where c.ColumnName == columnName select c).FirstOrDefault();
        }
        [Browsable(false)]
        public BaseForm ParentForm
        {
            get
            {
                return _parentForm;
            }
            set
            {
                _parentForm = value;
            }
        }
        [Category("Fcdbase 属性")]
        [Description("指示抽取数据的限制"), DefaultValue(100)]
        public int RecordLimit
        {
            get;
            set;
        }
        /// <summary>
        /// 设置数据源只读状态
        /// </summary>
        [Browsable(false)]
        public bool ReadOnly
        {

            set
            {
                if (this.Columns != null)
                {
                    foreach (DataItem di in this.Columns)
                    {
                        ParentForm.SetFormReadOnly(value, di.ColumnName);
                    }
                }
            }
        }
        [Category("Fcdbase 属性")]
        [Description("指示是否限制抽取数据,LogicalParent不为空时，不起作用"), DefaultValue(true)]
        public bool IsLimit
        {
            get;
            set;
        }
        [Category("Fcdbase 属性")]
        [Description("指示父数据源")]
        public DataSourceBinding LogicalParent
        {
            get
            {
                return _parent;
            }
            set
            {
                _parent = value;
            }
        }

        /// <summary>
        /// 指示是否自动执行查询。
        /// </summary>
        [Category("Fcdbase 属性"), DefaultValue(true)]
        [Description("指示是否自动执行查询")]
        public bool IsAutoQuery
        {
            get;
            set;
        }
        private bool _IsTable;
        /// <summary>
        /// 数据源名称。
        /// </summary>
        [Category("Fcdbase 属性")]
        [Description("指示生成网格还是基础控件")]
        public bool IsTable
        {
            get
            {
                return _IsTable;
            }
            set
            {
                _IsTable = value;
            }
        }
        /// <summary>
        /// 数据源名称。
        /// </summary>
        [Category("Fcdbase 属性")]
        [Description("Get or set object name.")]
        public string Name
        {
            get
            {
                if (this.Site != null)
                    return this.Site.Name;
                else
                    return "MasterdataSourceBinding";
            }
            set
            {
                if (this.Site == null)
                    return;
                if (string.IsNullOrEmpty(value))
                    return;

                this.Site.Name = value;
            }
        }
        private string _module;
        [Category("F1 Data Source"), DefaultValue(null), Description("Select what component the window shall be connected to."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("1. Component")]
        public string Module
        {
            get
            {
                return _module;
            }
            set
            {
                _module = value;
                CreateEntity();
            }
        }
        private string _logicalUnit;
        [Category("F1 Data Source"), DefaultValue(null), Description("Select what logical unit the window shall be connected to."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("2. Logical Unit")]
        public string LogicalUnit
        {
            get
            {
                return _logicalUnit;
            }
            set
            {
               // Type t = TypeX.GetType(value);
              //  if (t == null)
              //      throw new Exception("没有找到指定的逻辑单元，请检查是否输入有误");
                _logicalUnit = value;
                CreateEntity();
              //  this.DataSource = t;
            }
        }
        private string _viewName;
        [Category("F1 Data Source"), DefaultValue(null), Description("Select what database view the window shall be connected to."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("3. View")]
        public string ViewName
        {
            get
            {
                return _viewName;
            }
            set
            {
                _viewName = value;
                CreateEntity();
            }
        }
        [Category("F1 Data Source"), DefaultValue(null), Description("Select what package the window shall be connected to."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("4. Package")]
        public string PackageName
        {
            get
            ;
            set
            ;
        }
        [Category("F1 Data Source"), DefaultValue(null), Description("Enter additional where statements to limit the amount of populated data in the window."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("Default 'Where'")]
        public string DefaultWhere
        {
            get;

            set;
        }
       // private string _parentWhere;
        [Browsable(false)]
        public string ParentWhere
        {
            get
            {
                if (DesignMode)
                    return "";
                if (this.dataSource != null && !string.IsNullOrEmpty(this.dataSource.i_lsParentWhere))
                    return this.dataSource.i_lsParentWhere;
                else
                {
                    if (this.LogicalParent == null)
                        return "";
                    else
                    {
                        string where = "";
                        if (this.Columns != null)
                        {
                            foreach (DataItem di in this.Columns)
                            {
                                if (di.Flags == DataItemFlags.ParentKey)
                                {
                                    if (this.LogicalParent.Columns != null)
                                    {
                                        foreach (DataItem pDi  in this.LogicalParent.Columns)
                                        {
                                            if (di.ColumnName.ToLower() == pDi.ColumnName.ToLower())
                                            {
                                                IEntity en = this.LogicalParent.Current as IEntity;
                                                string sVal = "";
                                                if (en == null)
                                                    sVal = "";
                                                else
                                                {

                                                    if (en[pDi.ColumnName] != null)
                                                        sVal = en[pDi.ColumnName].ToString();
                                                }
                                                if (string.IsNullOrEmpty(where))
                                                    where = di.ColumnName + " = '" + sVal + "'";
                                                else
                                                    where = where + " and " + di.ColumnName + " = '" + sVal + "'";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        return where;
                    }
                }
            }
            set
            {
                if (this.dataSource != null)
                    this.dataSource.i_lsParentWhere = value;
            }
        }
        [Browsable(false)]
        public string UserWhere
        {
            get
            {
                if (this.dataSource != null)
                    return this.dataSource.i_lsUserWhere;
                else
                    return "";
            }
            set
            {
                if (this.dataSource != null)
                    this.dataSource.i_lsUserWhere = value;
            }
        }
        [Browsable(false)]
        public string UserOrderBy
        {
            get
            {
                if (this.dataSource != null)
                    return this.dataSource.i_sUserOrderBy;
                else
                    return "";
            }
            set{
                if (this.dataSource != null)
                    this.dataSource.i_sUserOrderBy = value;
            }
        }
        [Browsable(false)]
        public List<fnd_user_profile> QueryProfile
        {
            get;
            set;
        }
        [Browsable(false)]
        public List<fnd_user_profile> UserTemplates
        {
            get;
            set;
        }
        //protected override void OnDataError(BindingManagerDataErrorEventArgs e)
        //{
           
        //    base.OnDataError(e);
        //}
        //protected override void OnBindingComplete(BindingCompleteEventArgs e)
        //{
        //    e.Cancel = true;
        //    base.OnBindingComplete(e);
        //}
        public SalBoolean DataSourceUserWhereSet(SalString lsUserWhere)
        {
            UserWhere = lsUserWhere;
            return true;
        }
        public SalString DataSourceUserWhereGet()
        {
            SalString where= "";
            if (!string.IsNullOrEmpty(this.DefaultWhere))
                where = this.DefaultWhere;
            if (where.IsEmpty)
                where = this.ParentWhere;
            else
                if (!string.IsNullOrEmpty(this.ParentWhere))
                    where = where + " and " + this.ParentWhere;
            if (where.IsEmpty)
                where = this.UserWhere;
            else
                if (!string.IsNullOrEmpty(this.UserWhere))
                    where = where + " and " + this.UserWhere;
            return where;
        }
        public SalBoolean DataSourceUserOrderBy(SalString lsOrderBy)
        {
            this.UserOrderBy = lsOrderBy;
            return true;
        }
        public SalString DataSourceUserOrderByGet()
        {
            SalString orderby = this.vrtDataSourceUserOrderByGet();
            if (orderby.IsEmpty)
                orderby = this.UserOrderBy;
            else
            {
                if (!string.IsNullOrEmpty(this.UserOrderBy))
                    orderby = orderby + " , " + this.UserOrderBy;
            }
            return orderby;
        }
        [Category("F1 Data Source"), DefaultValue(null), Description("Enter an order by statement to automatically sort the populated data in the window. Use this with caution since this will have a performance impact on large data volumes."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("Default 'Order by'")]
        public string DefaultOrderBy
        {
            get;
            set;

        }
        [Category("F1 Allowed Operations"), DefaultValue(true), Description("Set this property to true to allow the user to add new records in the window."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("New")]
        public new bool AllowNew
        {
            get
            {
                return (this.SourceFlags & 64) != 0;
            }
            set
            {
                this.SourceFlags = (value ? (this.SourceFlags | 64) : (this.SourceFlags & -65));
            }
        }

        [Category("F1 Allowed Operations"), DefaultValue(true), Description("Set this property to true to allow the user to edit existing records in the window."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("Modify")]
        public new bool AllowEdit
        {
            get
            {
                return (this.SourceFlags & 128) != 0;
            }
            set
            {
                this.SourceFlags = (value ? (this.SourceFlags | 128) : (this.SourceFlags & -129));
            }
        }
        [Category("F1 Allowed Operations"), DefaultValue(true), Description("Set this property to true to allow the user to delete existing records in the window."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("Remove")]
        public new bool AllowRemove
        {
            get
            {
                return (this.SourceFlags & 256) != 0;
            }
            set
            {
                this.SourceFlags = (value ? (this.SourceFlags | 256) : (this.SourceFlags & -257));
            }
        }
        private int _sourceflags;
        [Browsable(false), Category("F1 Options"), DefaultValue(449), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), EditorBrowsable(EditorBrowsableState.Never)]
       
        public int SourceFlags
        {
            get
            {
                return _sourceflags;
            }
            set
            {
                _sourceflags = value;
            }
        }
        [Category("F1 Options"), DefaultValue(false), Description("Set this property to true if you want the client to send state machine events."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("State Machine"), EditorBrowsable(EditorBrowsableState.Never)]
        public bool StateMachine
        {
            get
            {
                return (this.SourceFlags & 8192) != 0;
            }
            set
            {
                this.SourceFlags = (value ? (this.SourceFlags | 8192) : (this.SourceFlags & -8193));
            }
        }
        private string _warnings;
        [Category("F1 Options"), DefaultValue(true), Description("Set this property to true if server warnings are handled in the window."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("Enable Warnings"), EditorBrowsable(EditorBrowsableState.Never)]
       
        public bool Warnings
        {
            get
            {
                return _warnings == "TRUE";
            }
            set
            {
                _warnings = (value ? "TRUE" : "FALSE");
            }
        }
        [Category("F1 Options"), DefaultValue(UpdatesSql.Standard), Description("Set this property to true if server warnings are handled in the window."), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible), DisplayName("Update"), EditorBrowsable(EditorBrowsableState.Never)]
        public UpdatesSql Updates { get; set; }
        [Browsable(false)]
        public UpdatesSql OldUpdate
        {
            get;
            set;
        }
        private SalNamedProperties m_namedProperties;
        //[Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        //public SalNamedProperties NamedProperties
        //{
        //    get
        //    {
        //        if (this.m_namedProperties == null)
        //        {
        //            this.m_namedProperties = new SalNamedProperties();
        //        }
        //        return this.m_namedProperties;
        //    }
        //}
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public bool PropertyChanged
        {
            get;
            set;
        }
        /// <summary>
        /// oolean = SalAnyRows(nFlagOn, nFlagOff) (返回 0 或者 1)
        //查询Datasource中是否存在有 'nFlagOn'状态的记录(状态包括: 1=Edited, 2=New, 3=MarkedDelete)
        //                        且不包括 'nFlagOff'的记录( 状态包括: 1=Edited, 2=New, 3=MarkedDelete,)
        /// </summary>
        /// <param name="?"></param>
        /// <returns></returns>
        public SalBoolean SalAnyRows(SalNumber nFlagOn, SalNumber nFlagOff)
        {
            IEntityList list = this.DataSource as IEntityList;
            if (list == null || list.Count == 0)
                return 0;
            SalBoolean res = 0;
            foreach (IEntity en in list)
            {
                if (nFlagOn > 0)
                {
                    switch (nFlagOn)
                    {
                        case 1:
                            if (en.Status == RecordStatus.Edit)
                                return 1;
                            break;
                        case 2:
                            if (en.Status == RecordStatus.New)
                                return 1;
                            break;
                        case 3:
                            if (en.Status == RecordStatus.Delete)
                                return 1;
                            break;
                    }
                }
                else if(nFlagOn == 0)
                {
                    switch (nFlagOff)
                    {
                        case 1:
                            if (en.Status != RecordStatus.Edit)
                                res = 1;
                            break;
                        case 2:
                            if (en.Status != RecordStatus.New)
                                res = 1;
                            break;
                        case 3:
                            if (en.Status != RecordStatus.Delete)
                                res = 1;
                            break;

                    }
                    return res;
                }
            }
            return 0;
        }



        /// <summary>
        /// 调用业务类的校验方法
        /// </summary>
        /// <param name="dataMember"></param>
        /// <param name="validObject"></param>
        /// <returns></returns>
        public bool Validate(string dataMember, object validObject)
        {
            
            string functionObject = null;
            if(Columns == null)
                return true;
            bool valid = true;
            foreach (DataItem dataItem in Columns)
            {
                if (!string.IsNullOrEmpty(dataItem.Validate))
                {

                    if (dataMember.Equals(dataItem.ColumnName) &&
                    !string.IsNullOrEmpty(dataItem.Validate))
                    {
                        functionObject = dataItem.Validate;
                        break;
                    }
                }
            }
            IEntity Entity = this.Current as IEntity;
            if (this.dataSource != null && Entity != null)
                return Entity.Validate(dataMember, validObject);
            return valid;
             
        }

        //[Browsable(false)]
        //[RefreshProperties(RefreshProperties.Repaint)]
        //[DefaultValue("")]
        //public new string DataMember
        //{
        //    get
        //    {
        //        return base.DataMember;
        //    }
        //    set
        //    {
        //        base.DataMember = value;
        //    }
        //}

        //[Browsable(false)]
        //[DefaultValue("")]
        //[RefreshProperties(RefreshProperties.Repaint)]
        //[AttributeProvider(typeof(IListSource))]
        //public new object DataSource
        //{
        //    get
        //    {
        //        return base.DataSource;
        //    }
        //    set
        //    {
        //        base.DataSource = value;
        //    }
        //}

        //[Browsable(false)]
        //[DefaultValue("")]
        //public new string Filter
        //{
        //    get
        //    {
        //        return base.Filter;
        //    }
        //    set
        //    {
        //        base.Filter = value;
        //    }
        //}

        //[Browsable(false)]
        //[DefaultValue("")]
        //public new string Sort
        //{
        //    get
        //    {
        //        return base.Sort;
        //    }
        //    set
        //    {
        //        base.Sort = value;
        //    }
        //}

        private List<DataSourceBinding> _details;
        [Browsable(false)]
        public List<DataSourceBinding> Details
        {
            get
            {
                if (_details == null)
                    _details = new List<DataSourceBinding>();

                return _details;
            }
        }

        private DataSourceBinding _parent;
        //[Browsable(false)]
        //internal DataSourceBinding Parent
        //{
        //    get
        //    {
        //        return _parent;
        //    }
        //    set
        //    {
        //        _parent = value;
        //    }
        //}

        //private BaseForm _parentForm;
        

        #endregion

        #region 构造函数
        private SalNumber _Identify = SalNumber.Random();
        public SalNumber Identify
        {
            get
            {
                return _Identify;
            }
        }
        public DataSourceBinding()
        {
            this.SourceFlags = 449;
            this.m_salWindow = new SalWindow(this);
            this.dataSource = new cDataSource(this);
            Columns = new List<DataItem>();
            InitializeComponent();
            
            //InitDataSource();
          //  CreateEntitiy();
            
        }
        public cDataSource Session
        {
            get { return this.dataSource; }
        }
        public ISalWindow _derived;
        public DataSourceBinding(IContainer container)
        {
            this.SourceFlags = 449;
            this.m_salWindow = new SalWindow(this);
            container.Add(this);
            InitializeComponent();
            this.dataSource = new cDataSource(this);
            Columns = new List<DataItem>();
          //  this.CurrentItemChanged += new EventHandler(DataSourceBinding_CurrentItemChanged);
            //InitDataSource();
         //   CreateEntitiy();
            this.IsAutoQuery = true;
            
            
        }
        public bool Binding = true;
       
        public DataSourceBinding(IContainer container,ISalWindow derived)
        {
            this.SourceFlags = 449;
            this.m_salWindow = new SalWindow(this);
            container.Add(this);
            Columns = new List<DataItem>();
            InitializeComponent();
            this.IsAutoQuery = true;
            //InitDataSource();
           // CreateEntitiy();
            this.dataSource = new cDataSource(this);
            this._derived = derived;
            this._derived.AttachMessageActions(this);
        }
        public string ObjectUnit
        {
            get { return this.Module + "." + this.LogicalUnit + "." + this.ViewName; }
        }
        public IEntity CreateEntity()
        {
            if (UserDesignMode || this.DesignMode)
                return null;
            if (string.IsNullOrEmpty(this.Module) || string.IsNullOrEmpty(this.LogicalUnit) || string.IsNullOrEmpty(this.ViewName))
            {
                //Fcdbas.Core.Log.XTrace.WriteLine("逻辑单元不能为空！Module:{0},LogicalUnit:{1},ViewName:{2}", this.Module, this.LogicalUnit, this.ViewName);
                return null;
            }
            if (this.dataSource == null)
            {
                Fcdbas.Core.Log.XTrace.WriteLine("数据源不能为空！Module:{0},LogicalUnit:{1},ViewName:{2}", this.Module, this.LogicalUnit, this.ViewName);
                return null;
            }
            //if (this.DataSource != null)
            //{
            //   // this.DataSource = this.dataSource.Entity;
            //    return this.DataSource;
            //}
            if (!string.IsNullOrEmpty(this.ObjectUnit) && this.ObjectUnit != "..")
            {
                Type t = TypeX.GetType(this.ObjectUnit,true);
                if (t == null)
                {
                    Fcdbas.Core.Log.XTrace.WriteLine(string.Format("没有找到指定的数据实体！ObjectType:{0}", this.ObjectUnit));
                    return null;
                    //throw new Exception("没有找到指定的逻辑单元");
                }
                object obj = TypeX.CreateInstance(t);
                if (obj is IEntity)
                {
                    //this.dataSource.Entity = obj as IEntity;
                    this.DataSource = obj;
                }
                else if (obj != null)
                    //throw new Exception("逻辑单元必须从Entitiy继承");
                    return null;
                return obj as IEntity;
            }
            else
            {
                Fcdbas.Core.Log.XTrace.WriteLine("逻辑单元不能为空！Module:{0},LogicalUnit:{1},ViewName:{2}", this.Module, this.LogicalUnit, this.ViewName);
            }
            return null;
        }
        public override object  AddNew()
        {
            if (IsNull)
                this.List.Clear();
 	        object obj = base.AddNew();
            IsAdding = false;
            IsNull = false;
            return obj;
        }
        public bool IsAdding
        {
            get;
            set;
        }
       
        protected override void OnAddingNew(AddingNewEventArgs e)
        {
            IsAdding = true;
            base.OnAddingNew(e);
        }
        public bool InitFlag = false;
        
        public void InitDataSource()
        {
            //this.DataSource = this.dataSource.Entity;
            this.dataSource.p_sModule = this.Module;
            this.dataSource.p_sLogicalUnit = this.LogicalUnit;
            this.dataSource.p_sPackageName = this.PackageName;
            this.dataSource.p_sViewName = this.ViewName;
            //this.dataSource.p_bWarnings = this.Warnings;
            this.dataSource.p_lsDefaultWhere = this.DefaultWhere;
            this.dataSource.p_nSourceFlags = this.SourceFlags;
            this.dataSource.p_sDefaultOrderBy = this.DefaultOrderBy;
            OldUpdate = Updates;
            this.IsAutoQuery = true;
            // if (!string.IsNullOrEmpty(this.ObjectUnit) && this.ObjectUnit != "..")
            //{
            //    Type t = TypeX.GetType(this.ObjectUnit);
            //    this.DataSource = t;
            //}
            InitFlag = true;
        }
        #endregion

        public List<string> GetEnums(string key)
        {
            return dataSource.DbSesseion.GetEnums(dataSource.Entity, key);
        }
        ///// <summary>
        ///// 是否自动抽取Detail数据
        ///// </summary>
        //[Browsable(false)]
        //public bool IsAutoPopulate
        //{
        //    get;
        //    set;
        //}

        #region IEditableBusinessObject 成员

        public bool IsDirty
        {
            get
            {
                if (this.DataSource == null ||
                    !(this.DataSource is DataTable))
                    return false;
                DataTable dataSource = ((DataTable)this.DataSource);

                foreach (DataRow row in dataSource.Rows)
                {
                    if (row.RowState == DataRowState.Added ||
                        row.RowState == DataRowState.Deleted ||
                        row.RowState == DataRowState.Modified ||
                        row.RowState == DataRowState.Detached)
                        return true;
                }

                if (_details == null ||
                    _details.Count <= 0)
                    return false;
                else
                {
                    foreach (DataSourceBinding detail in _details)
                    {
                        if (detail.IsDirty)
                            return true;
                    }

                    return false;
                }
            }
        }


        #endregion

        public Core.SalBoolean vrtDataRecordCheckModify(Core.IEntity entity)
        {
            if (this.DataRecordCheckModify != null)
            {
                cDataSource.DataRecordCheckModifyEventArgs dataRecordCheckModifyEventArgs = new cDataSource.DataRecordCheckModifyEventArgs(entity);
                this.DataRecordCheckModify(this, dataRecordCheckModifyEventArgs);
                if (dataRecordCheckModifyEventArgs.Handled)
                {
                    return dataRecordCheckModifyEventArgs.ReturnValue;
                }
            }
            return dataSource.DataRecordCheckModify(entity);
        }

        public Core.SalBoolean vrtDataRecordCheckNew(Core.IEntity entity)
        {
            if (this.DataRecordCheckNew != null)
            {
                cDataSource.DataRecordCheckNewEventArgs dataRecordCheckNewEventArgs = new cDataSource.DataRecordCheckNewEventArgs(entity);
                this.DataRecordCheckNew(this, dataRecordCheckNewEventArgs);
                if (dataRecordCheckNewEventArgs.Handled)
                {
                    return dataRecordCheckNewEventArgs.ReturnValue;
                }
            }
            return dataSource.DataRecordCheckNew(entity);
        }

        public Core.SalBoolean vrtDataRecordCheckRemove(Core.IEntity entity)
        {
            if (this.DataRecordCheckRemove != null)
            {
                cDataSource.DataRecordCheckRemoveEventArgs dataRecordCheckRemoveEventArgs = new cDataSource.DataRecordCheckRemoveEventArgs(entity);
                this.DataRecordCheckRemove(this, dataRecordCheckRemoveEventArgs);
                if (dataRecordCheckRemoveEventArgs.Handled)
                {
                    return dataRecordCheckRemoveEventArgs.ReturnValue;
                }
            }
            return dataSource.DataRecordCheckRemove(entity);
        }

        public Core.SalBoolean vrtDataRecordCheckRequired()
        {
            if (this.DataRecordCheckRequired != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataRecordCheckRequired(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataRecordCheckRequired();
        }

        public Core.SalNumber vrtDataRecordCopy(Core.SalNumber nWhat)
        {
            return true;
        }

        public Core.SalNumber vrtDataRecordDuplicate(Core.SalNumber nWhat)
        {
            return true;
        }

        public Core.SalBoolean vrtDataRecordExecuteModify(Core.IEntity entity)
        {
            if (this.DataRecordExecuteModify != null)
            {
                cDataSource.DataRecordExecuteModifyEventArgs dataRecordExecuteModifyEventArgs = new cDataSource.DataRecordExecuteModifyEventArgs(entity);
                this.DataRecordExecuteModify(this, dataRecordExecuteModifyEventArgs);
                if (dataRecordExecuteModifyEventArgs.Handled)
                {
                    return dataRecordExecuteModifyEventArgs.ReturnValue;
                }
            }
            return dataSource.DataRecordExecuteModify(entity);
        }
        public void OnDataRecordDuplicate(SalNumber nWhat)
        {
            if (DataRecordDuplicate != null)
            {
                cDataSource.DataRecordDuplicateEventArgs arg = new cDataSource.DataRecordDuplicateEventArgs(nWhat);
                DataRecordDuplicate(this, arg);
            }
        }
        public Core.SalBoolean vrtDataRecordExecuteNew(Core.IEntity entity)
        {
            if (this.DataRecordExecuteNew != null)
            {
                cDataSource.DataRecordExecuteNewEventArgs dataRecordExecuteNewEventArgs = new cDataSource.DataRecordExecuteNewEventArgs(entity);
                this.DataRecordExecuteNew(this, dataRecordExecuteNewEventArgs);
                if (dataRecordExecuteNewEventArgs.Handled)
                {
                    return dataRecordExecuteNewEventArgs.ReturnValue;
                }
            }
            return dataSource.DataRecordExecuteNew(entity);
        }

        public Core.SalBoolean vrtDataRecordExecutePLSqlLock(Core.IEntity entity)
        {
            return true;
        }

        public Core.SalBoolean vrtDataRecordExecuteRemove(Core.IEntity entity)
        {
            if (this.DataRecordExecuteRemove != null)
            {
                cDataSource.DataRecordExecuteRemoveEventArgs dataRecordExecuteRemoveEventArgs = new cDataSource.DataRecordExecuteRemoveEventArgs(entity);
                this.DataRecordExecuteRemove(this, dataRecordExecuteRemoveEventArgs);
                if (dataRecordExecuteRemoveEventArgs.Handled)
                {
                    return dataRecordExecuteRemoveEventArgs.ReturnValue;
                }
            }
            return dataSource.DataRecordExecuteRemove(entity);
        }

        public Core.SalBoolean vrtDataRecordExecuteStateEvent(Core.IEntity entity, Core.SalString sEvent)
        {
            return true;
        }

        public Core.SalNumber vrtDataRecordFetchEditedUser(ref Core.SalString lsAttr)
        {
            if (this.DataRecordFetchEditedUser != null)
            {
                cDataSource.DataRecordFetchEditedUserEventArgs dataRecordFetchEditedUserEventArgs = new cDataSource.DataRecordFetchEditedUserEventArgs(lsAttr);
                this.DataRecordFetchEditedUser(this, dataRecordFetchEditedUserEventArgs);
                if (dataRecordFetchEditedUserEventArgs.Handled)
                {
                    return dataRecordFetchEditedUserEventArgs.Return(ref lsAttr);
                }
            }
            return dataSource.DataRecordFetchEditedUser(ref lsAttr);
        }

        public Core.SalBoolean vrtDataRecordGetDefaults()
        {
            return true;
        }
        /// <summary>
        /// 取得编辑字段的内容
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public SalString DataRecordFetchEdited(IEntity entity)
        {
           // IEntity en =OldEntitys.Find(p => p["objid"].ToString() == entity["objid"].ToString());
          //  if (en == null)
            //    return "";
           return entity.GetDiffAttr(false);
        }
        /// <summary>
        /// 取得编辑字段的内容
        /// </summary>
        /// <returns></returns>
        public SalString DataRecordFetchEdited()
        {
            IEntity entity = this.Current as IEntity;
            if (entity == null)
                return "";
           // IEntity en = OldEntitys.Find(p => p["objid"].ToString() == entity["objid"].ToString());
           // if (en == null)
           //     return "";
            return entity.GetDiffAttr(false);
        }
        /// <summary>
        /// 取得新建字段的内容
        /// </summary>
        /// <returns></returns>
        public SalString DataRecordFetchNew()
        {
            IEntity entity = this.Current as IEntity;
            if (entity == null)
                return "";
            
            return entity.GetAttr(false);
        }
        
        public Core.SalNumber vrtDataRecordNew(Core.SalNumber nWhat)
        {
            //OldEntity = null;
            //OldEntitys.Clear();
            if (ParentForm != null)
                ParentForm.FireOnGridColumn();
            if (this.DataRecordNew != null)
            {
                cDataSource.DataRecordNewEventArgs dataRecordNewEventArgs = new cDataSource.DataRecordNewEventArgs(nWhat);
                this.DataRecordNew(this, dataRecordNewEventArgs);
                if (dataRecordNewEventArgs.Handled)
                {
                    return dataRecordNewEventArgs.ReturnValue;
                }
            }
            return dataSource.DataRecordNew(nWhat);
        }
       
        public Core.SalNumber vrtDataRecordPaste(Core.SalNumber nWhat)
        {
            return true;
        }

        public Core.SalBoolean vrtDataRecordPrepareNew(IEntity entity)
        {
            if (this.DataRecordPrepareNew != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataRecordPrepareNew(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataRecordPrepareNew(entity);
        }

       

        public Core.SalNumber vrtDataRecordRemove(IEntity entity)
        {
            //OldEntity = null;
            //OldEntitys.Clear();
            if (this.DataRecordRemove != null)
            {
                cDataSource.DataRecordRemoveEventArgs dataRecordRemoveEventArgs = new cDataSource.DataRecordRemoveEventArgs(entity);
                this.DataRecordRemove(this, dataRecordRemoveEventArgs);
                if (dataRecordRemoveEventArgs.Handled)
                {
                    return dataRecordRemoveEventArgs.ReturnValue;
                }
            }
            return dataSource.DataRecordRemove(entity);
        }

        public Core.SalNumber vrtDataRecordShowRequired(Core.SalWindowHandle hWndField)
        {
            return true;
        }

        public Core.SalNumber vrtDataRecordStateEvent(Core.SalNumber nWhat, Core.SalString sEvent)
        {
            return true;
        }

        public Core.SalNumber vrtDataRecordToFormUser(ref Core.SalString lsServerAttr, ref Core.SalBoolean bMarkAsEdited)
        {
            if (this.DataRecordToFormUser != null)
            {
                cDataSource.DataRecordToFormUserEventArgs dataRecordToFormUserEventArgs = new cDataSource.DataRecordToFormUserEventArgs(lsServerAttr, bMarkAsEdited);
                this.DataRecordToFormUser(this, dataRecordToFormUserEventArgs);
                if (dataRecordToFormUserEventArgs.Handled)
                {
                    return dataRecordToFormUserEventArgs.Return(ref lsServerAttr, ref bMarkAsEdited);
                }
            }
            return dataSource.DataRecordToFormUser(ref lsServerAttr, ref bMarkAsEdited);
        }

        public Core.SalBoolean vrtDataRecordValidate()
        {
            if (this.DataRecordValidate != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataRecordValidate(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataRecordValidate();
        }



        public Core.SalBoolean vrtDataSourceCheck(IEntity Entity)
        {
            if (this.DataSourceCheck != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceCheck(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceCheck(Entity);
        }

        public Core.SalNumber vrtDataSourceClear(Core.SalNumber nWhat, Core.SalNumber nParam)
        {
            return true;
        }

        public Core.SalBoolean vrtDataSourceClearIt(Core.SalNumber nParam)
        {
            if (this.DataSourceClearIt != null)
            {
                cDataSource.DataSourceClearItEventArgs dataSourceClearItEventArgs = new cDataSource.DataSourceClearItEventArgs(nParam);
                this.DataSourceClearIt(this, dataSourceClearItEventArgs);
                if (dataSourceClearItEventArgs.Handled)
                {
                    return dataSourceClearItEventArgs.ReturnValue;
                }
            }
            return dataSource.DataSourceClearIt(nParam);

        }
       

        public Core.SalNumber vrtDataSourceDetailModified(Core.SalBoolean bDirty)
        {
            return true;
        }

        public Core.SalBoolean vrtDataSourceExecuteMarkCommitted()
        {
            
            this.dataSource.DataSourceExecuteMarkCommitted();
            return true;
        }

        public Core.SalBoolean vrtDataSourceExecuteMarkRollback()
        {
            this.dataSource.DataSourceExecuteMarkRollback();
            return true;
        }

        public Core.SalBoolean vrtDataSourceExecutePrepareRollback()
        {
            this.dataSource.DataSourceExecutePrepareRollback();
            return true;
        }

        public Core.SalNumber vrtDataSourceExecuteSqlCount(Core.SalString lsStmt)
        {
            return true;
        }

        public Core.SalBoolean vrtDataSourceExecuteSqlDelete(IEntity Entitiy)
        {
            if (this.DataSourceExecuteSqlDelete != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceExecuteSqlDelete(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceExecuteSqlDelete(Entitiy);
        }

        public Core.SalBoolean vrtDataSourceExecuteSqlInsert(IEntity Entity)
        {
            if (this.DataSourceExecuteSqlInsert != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceExecuteSqlInsert(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceExecuteSqlInsert(Entity);
        }

      

        public Core.SalBoolean vrtDataSourceExecuteSqlLock()
        {
            throw new NotImplementedException();
        }

       

       

        public Core.SalBoolean vrtDataSourceExecuteSqlStateEvent(Core.SalString sEvent)
        {
            throw new NotImplementedException();
        }

        public Core.SalBoolean vrtDataSourceExecuteSqlUpdate(IEntity Entitiy)
        {
            if (this.DataSourceExecuteSqlUpdateEvent != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceExecuteSqlUpdateEvent(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceExecuteSqlUpdate(Entitiy);
        }
        /// <summary>
        /// 修改记录
        /// </summary>
        /// <param name="entity"></param>
        public void DataRecordModified(IEntity entity)
        {
            if (entity != null && entity.Status == RecordStatus.Normal)
            {
                IEntity OldEntity = entity.CloneEntity(false);
                OldEntitys.Add(OldEntity);
                entity.Status = RecordStatus.Edit;
                Fcdbas.Core.Windows.SalWindow.FireWindowActions(_parentForm, Fcdbas.Platform.Const.AM_DataSourceFieldModified, 1, this.Identify);
                
            }
        }
        public Core.SalNumber vrtDataSourceFieldModified()
        {
            if (this.DataSourceFieldModified != null)
            {
                cDataSource.ReturnEventArgsSalNumber fndReturnEventArgsSalNumber = new cDataSource.ReturnEventArgsSalNumber();
                this.DataSourceFieldModified(this, fndReturnEventArgsSalNumber);
                if (fndReturnEventArgsSalNumber.Handled)
                {
                    return fndReturnEventArgsSalNumber.ReturnValue;
                }
            }
            if (this.Current != null)
            {
                IEntity entity = this.Current as IEntity;
                if (entity != null && entity.Status == RecordStatus.Normal)
                {
                    IEntity OldEntity = entity.CloneEntity(false);
                    OldEntitys.Add(OldEntity);
                    entity.Status = RecordStatus.Edit;
                }
            }
            if (this.Current == null)
                return 0;
            return dataSource.DataSourceFieldModified();
        }

      

        public Core.SalNumber vrtDataSourceInquireSave()
        {
            return 1;// throw new NotImplementedException();
        }

        public Core.SalNumber vrtDataSourceIsDirty(Core.SalNumber nWhat)
        {
            return 1;// throw new NotImplementedException();
        }

        public Core.SalNumber vrtDataSourceMarkRollback()
        {
            //if (OldEntity != null)
            //{
            //    IEntity entity = this.Current as IEntity;
            //    if (entity != null)
            //    {
            //        entity.CopyFrom(OldEntity, false);
            //        //this.ResetCurrentItem();
            //    }
            //}
            return dataSource.DataSourceMarkRollback();
        }

        public Core.SalNumber vrtDataSourcePopulate(Core.SalNumber nWhat, Core.SalNumber nParam)
        {
            return 1; //throw new NotImplementedException();
        }

        /// <summary>
        /// 手工新增加一条记录
        /// </summary>
        public void AddNewRecord()
        {
            this.Session.vrtDataRecordNew(1);
            this.ResetCurrentItem();
        }
        public void QuickAddNew()
        {
            this.Session.QuickAddNew();
        }
        public Core.SalNumber vrtDataSourcePrepareRollback()
        {
            return 1;// throw new NotImplementedException();
        }

        private bool IsNull;
        /// <summary>
        ///  带条件刷新记录 
        /// </summary>
        /// <param name="lsUserWhere"></param>
        /// <returns></returns>
        public SalBoolean DataSourceRefresh(SalString lsUserWhere,SalString lsOrderBy)
        {
            if (string.IsNullOrEmpty(this.ViewName))
            {
                OnFetchRowsDone(this, 0);
                return false;
            }
            if (!Fcdbas.WinUI.Common.Security.IsViewAvaliable(Fcdbas.WinUI.Common.AppEnvironment.Session.USER_ID, this.ViewName))
            {
                Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage("没有查询视图[%%1]的权限，请联系系统管理员。", ViewName);
                OnFetchRowsDone(this, 0);
                return 0;
            }
            if (this.DataSourceDataChanged != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceDataChanged(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    OnFetchRowsDone(this, 0);
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            Binding = true;
            if (this.Details != null && this.Details.Count > 0)
            {
                foreach (DataSourceBinding ds in this.Details)
                    ds.ParentWhere = "";
            }
            SalNumber res = dataSource.DataSourceRefresh(lsUserWhere,lsOrderBy);

            if (dataSource.DataSource == null)
            {
                Binding = false;
                OnFetchRowsDone(this, 0);
                return 0;
            }
            //if (dataSource.DataSource is IList)
            //{
            //    if (((IList)(dataSource.DataSource)).Count != 0)
            //    {
            //        IsNull = false;
            //        this.DataSource = dataSource.DataSource;
            //        //((IList)(dataSource.DataSource)).Clear();
            //    }
            //    else
            //    {
            //        IsNull = true;
            //        zeroList = dataSource.DataSource;
            //        if (this.DataSource is IList)
            //        {
            //            if (((IList)(this.DataSource)).Count != 0)
            //                this.DataSource = dataSource.DataSource;
            //            else
            //            {
            //                this.DataSource = CreateEntity();
            //                this.ResetBindings(false);
            //            }
            //        }

            //    }
            //}
            //else
            this.Session.RecordRefresh = true;
            if (dataSource.DataSource != null && dataSource.DataSource.Count > 0)
            {
                
                this.DataSource = dataSource.DataSource;
                this.ParentForm.ResumeBinding(this);
                this.ResetBindings(false);
                OnFetchRowsDone(this, res);
            }
            else
            {
                OnFetchRowsDone(this, 0);
                try
                {
                    this.DataSource = CreateEntity();
                    if(ParentForm!= null)
                        ParentForm.ClearGridEmptyRow();
                }
                catch
                {

                }
            }
            this.Session.RecordRefresh = false;
            Binding = false;
            return res;
        }
        /// <summary>
        /// 刷新指定记录的数据
        /// </summary>
        /// <param name="entity">要刷新的记录</param>
        /// <returns>成功返回true</returns>
        public SalBoolean DataRecordRefresh(IEntity entity)
        {
            SalBoolean res= dataSource.DataRecordRefreshEntity(entity);
            if(res)
                this.ResetBindings(false);
            return res;
        }
        public void ResumeFormBinding()
        {
            if(this.ParentForm != null)
                this.ParentForm.ResumeBinding(this);
        }
        /// <summary>
        /// 如果nWhat=0,则判断该Datasource是否允许保存(存在有修改,新增或者删除的状态); 如果nWhat = 1: 执行保存,调用框架的保存)
        /// </summary>
        /// <param name="nWhat"></param>
        /// <returns></returns>
        public SalBoolean DataSourceSave(SalNumber nWhat)
        {
            if (nWhat == 0)
            {
                if (DataSource == null || this.Count == 0)
                    return 0;

                IEntityList list = DataSource as IEntityList;
                foreach (IEntity en in list)
                {
                    if (en.Status != RecordStatus.Normal)
                        return 1;
                }
                return 0;
            }
            else
            {
                
                return dataSource.DataSourceSave(1);
            }
        }
        public Core.SalNumber DataSourcePopulate(DataSourcePopulate nWhat)
        {
            return vrtDataSourceRefresh(nWhat);
        }
        public Core.SalNumber PrepareQuery()
        {
            if (this.DataSourceDataChanged != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceDataChanged(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            dataSource.PrepareQuery();
            return 1;
        }
        public void BindFromDatasource(IEntityList dsList)
        {
            Binding = true;

            if (dsList == null)
            {
                Binding = false;
                OnFetchRowsDone(this, 0);
                return ;
            }
            
            this.Session.RecordRefresh = true;
            if (dsList != null && dsList.Count > 0)
            {
                this.DataSource = dsList;
                this.ParentForm.ResumeBinding(this);

                this.ResetBindings(false);
                OnFetchRowsDone(this, dsList.Count);
            }
            else
            {
                OnFetchRowsDone(this, 0);
                try
                {
                    this.DataSource = CreateEntity();

                    this.DataSource = dsList;
                    if (ParentForm != null)
                        ParentForm.ClearGridEmptyRow();
                }
                catch (Exception ex)
                {
                    Fcdbas.Core.Log.XTrace.WriteException(ex);
                }
            }
            this.Session.RecordRefresh = false;
            Binding = false;
        }
        /// <summary>
        /// 数据刷新
        /// </summary>
        /// <param name="nWhat">3重新抽取,1抽取下一段,2抽取所有,4刷新当前对象</param>
        /// <returns></returns>
        public Core.SalNumber vrtDataSourceRefresh(DataSourcePopulate nWhat)
        {
            if (string.IsNullOrEmpty(this.ViewName))
            {
                OnFetchRowsDone(this, 0);
                return false;
            }
            if (!Fcdbas.WinUI.Common.Security.IsViewAvaliable(Fcdbas.WinUI.Common.AppEnvironment.Session.USER_ID, this.ViewName))
            {
                Fcdbas.WinUI.Common.WinTranslate.GetTranslate().ShowMessage("没有查询视图[%%1]的权限，请联系系统管理员。", ViewName);
                OnFetchRowsDone(this, 0);
                return 0;
            }
            if (this.DataRecordCurrentRefresh != null && nWhat == Controls.DataSourcePopulate.Current)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataRecordCurrentRefresh(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    OnFetchRowsDone(this, 0);
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            if (this.DataSourceDataChanged != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceDataChanged(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    OnFetchRowsDone(this, 0);
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            Binding = true;
            SalNumber res= dataSource.DataSourceRefresh(nWhat);
            if (dataSource.DataSource == null)
            {
                Binding = false;
                OnFetchRowsDone(this, 0);
                return 0;
            }
            //if (dataSource.DataSource is IList)
            //{
            //    if (((IList)(dataSource.DataSource)).Count != 0)
            //    {
            //        IsNull = false;
            //        this.DataSource = dataSource.DataSource;
            //        //((IList)(dataSource.DataSource)).Clear();
            //    }
            //    else
            //    {
            //        IsNull = true;
            //        zeroList = dataSource.DataSource;
            //        if (this.DataSource is IList)
            //        {
            //            if (((IList)(this.DataSource)).Count != 0)
            //                this.DataSource = dataSource.DataSource;
            //            else
            //            {
            //                this.DataSource = CreateEntity();
            //                this.ResetBindings(false);
            //            }
            //        }
                    
            //    }
            //}
            //else
            this.Session.RecordRefresh = true;
            if (dataSource.DataSource != null && dataSource.DataSource.Count > 0)
            {
                this.DataSource = dataSource.DataSource;
                this.ParentForm.ResumeBinding(this);
                
                this.ResetBindings(false);
                OnFetchRowsDone(this, res);
            }
            else
            {
                OnFetchRowsDone(this, 0);
                try
                {
                    this.DataSource = CreateEntity();
                    
                    this.DataSource = dataSource.DataSource;
                    if (ParentForm != null)
                    {
                        ParentForm.ClearGridEmptyRow();

                        ParentForm.ClearDetailData(this);
                    }
                }
                catch(Exception ex)
                {
                    Fcdbas.Core.Log.XTrace.WriteException(ex);
                }
            }
            this.Session.RecordRefresh = false;
            Binding = false;
            return res;
        }

        public Core.SalNumber vrtDataSourceSave(Core.SalNumber nWhat)
        {
            if (this.DataSourceSaves != null)
            {
                cDataSource.DataSourceSaveEventArgs dataSourceSaveEventArgs = new cDataSource.DataSourceSaveEventArgs(nWhat);
                this.DataSourceSaves(this, dataSourceSaveEventArgs);
                if (dataSourceSaveEventArgs.Handled)
                {
                    return dataSourceSaveEventArgs.ReturnValue;
                }
            }
            bool Remove = dataSource.IsDelete;
            int res= dataSource.DataSourceSave(nWhat);
            
            if (res >= 0 )
            {
                this.Binding = true;
               // this.RemoveCurrent();
                this.ResetBindings(false);
                this.Binding = false;
            }
            return res;
        }

        public Core.SalBoolean vrtDataSourceSaveCheck(IEntity Entity)
        {
            if (this.DataSourceSaveCheck != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceSaveCheck(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceSaveCheck(Entity);
        }

        //public virtual SalBoolean vrtDataSourceCheck(IEntity Entity)
        //{
        //    if (this.DataSourceCheckEvent != null)
        //    {
        //        cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
        //        this.DataSourceCheckEvent(this, fndReturnEventArgsSalBoolean);
        //        if (fndReturnEventArgsSalBoolean.Handled)
        //        {
        //            return fndReturnEventArgsSalBoolean.ReturnValue;
        //        }
        //    }
        //    return dataSource.DataSourceCheck(Entity);
        //}

       

        public Core.SalNumber vrtDataSourceSaveMarkCommitted()
        {
            if (this.DataSourceSaveMarkCommitted != null)
            {
                cDataSource.ReturnEventArgsSalNumber fndReturnEventArgsSalNumber = new cDataSource.ReturnEventArgsSalNumber();
                this.DataSourceSaveMarkCommitted(this, fndReturnEventArgsSalNumber);
                if (fndReturnEventArgsSalNumber.Handled)
                {
                    return fndReturnEventArgsSalNumber.ReturnValue;
                }
            }
            return dataSource.DataSourceSaveMarkCommitted();
        }

        public Core.SalBoolean vrtDataSourceSaveModified(IEntity Entity)
        {
            if (this.DataSourceSaveModified != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceSaveModified(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceSaveModified(Entity);
        }

        public Core.SalBoolean vrtDataSourceSaveNew(IEntity Entity)
        {
            if (this.DataSourceSaveNew != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceSaveNew(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceSaveNew(Entity);
        }
        public Core.SalString vrtDataSourceUserWhereGet()
        {
            if (this.DataSourceUserWhere != null)
            {
                cDataSource.ReturnEventArgsSalString fndReturnEventArgsSalString = new cDataSource.ReturnEventArgsSalString();
                this.DataSourceUserWhere(this, fndReturnEventArgsSalString);
                if (fndReturnEventArgsSalString.Handled)
                {
                    return fndReturnEventArgsSalString.ReturnValue;
                }
            }
            return dataSource.DataSourceUserWhereGet();
        }
        public Core.SalBoolean vrtDataSourceSaveRemoved(IEntity Entity)
        {
            if (this.DataSourceSaveRemoved != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceSaveRemoved(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceSaveRemoved(Entity);
        }

        public Core.SalString vrtDataSourceUserOrderByGet()
        {
            return this.DefaultOrderBy;
        }

        //public Core.SalString vrtDataSourceUserWhereGet()
        //{
        //    return this.DefaultWhere;
        //}
        public virtual SalString vrtDataSourceUserFieldGet()
        {
            StringBuilder sb = new StringBuilder();
            foreach (DataItem di in this.Columns)
            {
                if (!string.IsNullOrEmpty(di.RefFunction))
                {
                    sb.Append(di.RefFunction);
                    sb.Append(" as ");
                    sb.Append(di.ColumnName);
                    sb.Append(",");
                }

            }
            if (sb.Length > 0)
                sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
        public Core.SalBoolean vrtDataSourceValidate()
        {
            if (this.DataSourceValidate != null)
            {
                cDataSource.ReturnEventArgsSalBoolean fndReturnEventArgsSalBoolean = new cDataSource.ReturnEventArgsSalBoolean();
                this.DataSourceValidate(this, fndReturnEventArgsSalBoolean);
                if (fndReturnEventArgsSalBoolean.Handled)
                {
                    return fndReturnEventArgsSalBoolean.ReturnValue;
                }
            }
            return dataSource.DataSourceValidate();
        }


        public event WindowActionsEventHandler WindowActions
        {
            add
            {
                this.m_salWindow.AddWindowActions(value);
            }
            remove
            {
                this.m_salWindow.RemoveWindowActions(value);
            }
        }

        public object Derived
        {
            get { return this._derived; }
        }

        public void AttachMessageActions(ISalWindow target)
        {
            this.m_salWindow.AddWindowActions(target);
        }

        public void DefaultWndProc(ref Message m)
        {
            //base.WndProc(ref m);
            
        }

        public SalWindow GetSalWindowImpl()
        {
            return m_salWindow;
        }

        public int GetWindowType()
        {
            return 0;
        }
    }

    public class CurrentSavedEventArgs : EventArgs
    {
        public CurrentSavedEventArgs()
        {
        }

        public CurrentSavedEventArgs(object savedObject)
        {
        }

        public object SavedObject { get; set; }
    }

    public class DataSourceSavedEventArgs : EventArgs
    {
        public DataSourceSavedEventArgs()
        {
        }

        public DataSourceSavedEventArgs(DataTable savedDataSource)
        {
        }

        public DataTable SavedDataSource { get; set; }
    }

    public class CurrentRemovedEventArgs : EventArgs
    {
        public CurrentRemovedEventArgs()
        {
        }

        public CurrentRemovedEventArgs(object removedObject)
        {
        }

        public object RemovedObject { get; set; }
    }
}
